<template>
  <div class="role-management">
    <div class="page-header">
      <h2>Role Management</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>Add Role
      </el-button>
    </div>

    <!-- Role List -->
    <el-card class="list-card">
      <el-table
          v-loading="loading"
          :data="roleList"
          border
          stripe
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Role Name" width="150" />
        <el-table-column prop="description" label="Description" />
        <el-table-column label="Permissions" width="300">
          <template #default="{ row }">
            <el-tag
                v-for="permission in row.permissions"
                :key="permission"
                class="permission-tag"
            >
              {{ permissionLabels[permission] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="Create Time" width="180" />
        <el-table-column label="Operation" fixed="right" width="150">
          <template #default="{ row }">
            <el-button
                type="primary"
                link
                @click="handleEdit(row)"
            >
              Edit
            </el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(row)"
                :disabled="row.name === 'ADMIN' || row.name === 'USER'"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Role Form Dialog -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="Role Name" prop="name">
          <el-input
              v-model="form.name"
              placeholder="Please input role name"
              :disabled="form.name === 'ADMIN' || form.name === 'USER'"
          />
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="Please input role description"
          />
        </el-form-item>
        <el-form-item label="Permissions" prop="permissions">
          <el-checkbox-group v-model="form.permissions">
            <el-checkbox
                v-for="permission in availablePermissions"
                :key="permission"
                :label="permission"
            >
              {{ permissionLabels[permission] }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitLoading"
          >
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import type { Role, CreateRoleRequest, UpdateRoleRequest } from '../../types/user'
import axios from '../../utils/axios'

// State
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const roleList = ref<Role[]>([])

// Available permission list
const availablePermissions = [
  'USER_VIEW',
  'USER_EDIT',
  'USER_DELETE',
  'ROLE_VIEW',
  'ROLE_EDIT',
  'ROLE_DELETE',
  'LOG_VIEW',
  'SYSTEM_SETTINGS'
]

// Permission name mapping (English to Chinese - Should remain in English)
const permissionLabels = {
  'USER_VIEW': 'View User',
  'USER_EDIT': 'Edit User',
  'USER_DELETE': 'Delete User',
  'ROLE_VIEW': 'View Role',
  'ROLE_EDIT': 'Edit Role',
  'ROLE_DELETE': 'Delete Role',
  'LOG_VIEW': 'View Logs',
  'SYSTEM_SETTINGS': 'System Settings'
}

// Form
const formRef = ref<FormInstance>()

const form = reactive<CreateRoleRequest & UpdateRoleRequest>({
  name: '',
  description: '',
  permissions: []
})

// Computed properties
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? 'Add Role' : 'Edit Role'
})

// Form validation rules
const rules = {
  name: [
    { required: true, message: 'Please enter role name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Length must be between 2 and 50 characters', trigger: 'blur' }
  ],
  description: [
    { required: true, message: 'Please enter role description', trigger: 'blur' },
    { max: 200, message: 'Description cannot exceed 200 characters', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: 'Please select permissions', trigger: 'change' },
    { type: 'array', min: 1, message: 'Please select at least one permission', trigger: 'change' }
  ]
}

// Methods
const fetchRoleList = async () => {
  loading.value = true
  console.log('===== Retrieving role list =====')

  // Check token and authorization header
  const token = localStorage.getItem('token')
  console.log('Current token existence status:', !!token)

  try {
    // Use axios instead of fetch to leverage the global interceptor
    const response = await axios.get('/api/admin/roles')
    console.log('Successfully retrieved role list:', response.data.length, ' roles')
    roleList.value = response.data
  } catch (error: any) {
    console.error('Failed to retrieve role list:', error)
    ElMessage.error('Failed to retrieve role list')
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.name = ''
  form.description = ''
  form.permissions = []
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Role) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await axios.post('/api/admin/roles', form)
          ElMessage.success('Successfully added role')
        } else {
          await axios.put(`/api/admin/roles/${form.id}`, form)
          ElMessage.success('Successfully edited role')
        }
        dialogVisible.value = false
        fetchRoleList()
      } catch (error: any) {
        ElMessage.error(
            error.response?.data?.message ||
            (dialogType.value === 'add' ? 'Failed to add role' : 'Failed to edit role')
        )
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm(
        'Are you sure you want to delete this role? This action cannot be undone.',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
    )

    await axios.delete(`/api/admin/roles/${row.id}`)
    ElMessage.success('Successfully deleted role')
    fetchRoleList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || 'Failed to delete role')
    }
  }
}

// Lifecycle hooks
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.list-card {
  margin-bottom: 20px;
}

.permission-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>